/*
 * C/C++ KLIB Project
 * 
 * Copyright (c) 2012 Ken Zhang (cpp.china@gmail.com)
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA  02111-1307  USA
 *
 */


#include <stdlib.h>
#include <string.h>
#include "klib.h"
#include "types.h"

#define MAX_STACK_COUNT		1024

typedef struct _stack_t {
	void *buffer;
	int size;
	int pos;
} stack_t;

stack_t *_klibc_g_stacks[MAX_STACK_COUNT] = { 0 };

int stack_valid(int handle)
{
	if (_klibc_g_stacks && handle >= 0 && handle < MAX_STACK_COUNT) {
		if (_klibc_g_stacks[handle]) {
			return 1;
		}
	}
	return 0;
}

int stack_create(size_t size)
{
	stack_t *s;
	int i;
	if (size > 0) {
		for (i = 0; i < MAX_STACK_COUNT; i++) {
			if (!_klibc_g_stacks[i]) {
				s = (stack_t *)malloc(sizeof(stack_t));
				s->buffer = malloc(size);
				s->size = size;
				s->pos = 0;
				_klibc_g_stacks[i] = s;
				return i;
			}
		}
	}
	return -1;
}

void stack_destroy(int handle)
{
	if (stack_valid(handle)) {
		if (_klibc_g_stacks[handle]) {
			free(_klibc_g_stacks[handle]->buffer);
			free(_klibc_g_stacks[handle]);
			_klibc_g_stacks[handle] = NULL;
		}
	}
}

int stack_push(int handle, const void *data, size_t width)
{
	stack_t *s;
	if (stack_valid(handle)) {
		s = _klibc_g_stacks[handle];
		if (s != NULL && s->buffer != NULL) {
			if (s->pos + width > s->size) {
				// stack overflow
				return -2;
			}
			else {
				memcpy((byte *)s->buffer + s->pos, data, width);
				s->pos += width;
				return 0;
			}
		}
	}
	return -1;
}

int stack_pop(int handle, void *data, size_t width)
{
	stack_t *s;
	if (stack_valid(handle)) {
		s = _klibc_g_stacks[handle];
		if (s != NULL && s->buffer != NULL) {
			if (s->pos < width) {
				// no enough data to popup
				return -2;
			}
			else {
				memcpy(data, (byte *)s->buffer + s->pos - width, width);
				s->pos -= width;
				return 0;
			}
		}
	}
	return -1;
}

int stack_push_int(int handle, int value)
{
	return stack_push(handle, &value, sizeof(int));
}

int stack_pop_int(int handle, int *value)
{
	return stack_pop(handle, value, sizeof(int));
}

